package com.simtek.simplayer.utils;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.HashMap;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreProtocolPNames;
import org.json.JSONException;
import org.json.JSONObject;

import com.simtek.simplayer.entry.VideoPlayEntry;
import com.simtek.simplayer.entry.YoutubeUrlMeta;

public class YoutubeUtils {

	public static void loadYoutubeInfo(VideoPlayEntry entry) {
		if (entry == null) {
			return;
		}

		try {
			String url = "http://www.youtube.com/watch?v=" + entry.getVideoSrc();

			// Get the HTML response
			String userAgent = "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:8.0.1)";
			HttpClient client = new DefaultHttpClient();
			client.getParams().setParameter(CoreProtocolPNames.USER_AGENT, userAgent);

			HttpGet request = new HttpGet(url);

			HttpResponse response = client.execute(request);

			int code = response.getStatusLine().getStatusCode();
			if (code == 200) {
				InputStream in = response.getEntity().getContent();
				BufferedReader reader = new BufferedReader(new InputStreamReader(in));

				StringBuilder str = new StringBuilder();
				String line = null;
				while ((line = reader.readLine()) != null) {
					str.append(line.replace("\\u0026", "&"));
				}
				in.close();

				extractInfo(entry, str.toString());
			} else {
				entry.setFailed(true);
			}
		} catch (Throwable e) {
			e.printStackTrace();
		} finally {

		}
	}

	/**
	 * <code>
	{
    "uid": "yQobySFx_h9oFwsBV0KGdg",
    "ldpj": "-36",
    "account_playback_token": "QUFFLUhqbGxKY3FOb2plZHV0cXlYbVBKby03WDNjT2FNd3xBQ3Jtc0tuckpUTGhHa2dmbF96V1YxRHllUm1JaUlOUGVxNzVfMG5zSjlsR2R2MU1nT3M0eExHUzdocm1aS1RXVGdDUmdPZTY1UHoxN2dWeFhBQ3k5YjBQUW8yYWhyVUVlWkVfVmNEbk9IcU1FYTAwZUl2V01vNA==",
    "cos": "Windows",
    "aid": "P-zpxzJw0gU",
    "eventid": "mZyzU8-3D4L94QLHg4DQBg",
    "vq": "auto",
    "hl": "en_US",
    "timestamp": 1404279961,
    "baseUrl": "http:\/\/googleads.g.doubleclick.net\/pagead\/viewthroughconversion\/962985656\/",
    "url_encoded_fmt_stream_map": "type=video%2Fmp4%3B+codecs%3D%22avc1.64001F%2C+mp4a.40.2%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ratebypass%3Dyes%26ipbits%3D0%26signature%3D6600B1DFDD04E4CB94A1045DB3C7C27E4C725ABD.94362EA9CA3F8E7C24096DAF5C2C1704D5824DE9%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D22%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=22&fallback_host=tc.v16.cache1.googlevideo.com&quality=hd720,type=video%2Fwebm%3B+codecs%3D%22vp8.0%2C+vorbis%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ratebypass%3Dyes%26ipbits%3D0%26signature%3D0C5866C548B209F483EA78240B69A4101EA10870.503B473709CC17527B3EC0F277D938153352FB8A%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D43%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=43&fallback_host=tc.v17.cache5.googlevideo.com&quality=medium,type=video%2Fmp4%3B+codecs%3D%22avc1.42001E%2C+mp4a.40.2%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Cratebypass%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ratebypass%3Dyes%26ipbits%3D0%26signature%3D9765A5B0932919E116BB70789E013C209A7C8725.DAFAFF26310F702AA55AC3829CC64E204577DB52%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D18%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=18&fallback_host=tc.v20.cache7.googlevideo.com&quality=medium,type=video%2Fx-flv&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ipbits%3D0%26signature%3D02500114857EDE4EC7B68EC087728E0A45A4BA5F.A591812AC50B63DEBAFA85D7E2D04B4DCFCB80A6%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D5%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=5&fallback_host=tc.v20.cache1.googlevideo.com&quality=small,type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ipbits%3D0%26signature%3D5246E3FF5387A04B44E36002D0FA9152575FAFF7.A6B0074D5ED4BDCB60381A9C2A3CF2B067DC8BAD%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D36%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=36&fallback_host=tc.v11.cache1.googlevideo.com&quality=small,type=video%2F3gpp%3B+codecs%3D%22mp4v.20.3%2C+mp4a.40.2%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Did%252Cip%252Cipbits%252Citag%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26mws%3Dyes%26mv%3Dm%26ipbits%3D0%26signature%3D7C150403AC7F1880DD8A3553875128CAD1D08836.E64356D4B97BC123E30FC87E5D6FAB5B0CEB863E%26key%3Dyt5%26ip%3D123.21.12.150%26upn%3D8mSEnOzVIOM%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D17%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=17&fallback_host=tc.v10.cache6.googlevideo.com&quality=small",
    "fexp": "902408,906010,913587,924213,924217,924222,930008,930811,931324,934024,934030",
    "title": "Trên tay tai nghe HTC mini +",
    "adaptive_fmts": "lmt=1403869322695457&index=711-1246&bitrate=3897643&size=1920x1080&type=video%2Fmp4%3B+codecs%3D%22avc1.640028%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869322695457%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3DF2EB1FEFC26C05C0B19BDA68012B8015DFE34C50.63F6A6861D3C226DD8362D3277A6DB714D65C9FA%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D137%26clen%3D74096956%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=137&clen=74096956&init=0-710,lmt=1404096540868873&index=235-962&bitrate=1906240&size=1920x1080&type=video%2Fwebm%3B+codecs%3D%22vp9%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404096540868873%26mv%3Dm%26dur%3D208.275%26ipbits%3D0%26signature%3D7454A29EE9E3714F9EEF2BC67C1FE3EB80B5DB0E.5633400E85BFC66DDCE99FBE1573E5F40C003EA5%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D248%26clen%3D38292840%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=248&clen=38292840&init=0-234,lmt=1403869322328732&index=709-1244&bitrate=1920463&size=1280x720&type=video%2Fmp4%3B+codecs%3D%22avc1.4d401f%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869322328732%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3D09FCDD30610AC43363411A50BDF22D9E0A53BB65.989DC5AC6E2C8EB238BF09961F9426F53FE22757%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D136%26clen%3D35656432%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=136&clen=35656432&init=0-708,lmt=1404096471529383&index=235-950&bitrate=1123607&size=1280x720&type=video%2Fwebm%3B+codecs%3D%22vp9%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404096471529383%26mv%3Dm%26dur%3D208.275%26ipbits%3D0%26signature%3D68F554AC14E739074E71B0E460D7C1541660EC79.1373330A1E9445051738BB57DF7E3F84E27010F7%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D247%26clen%3D22785268%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=247&clen=22785268&init=0-234,lmt=1403869312889029&index=709-1244&bitrate=1035666&size=854x480&type=video%2Fmp4%3B+codecs%3D%22avc1.4d401f%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869312889029%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3D40112AF1A90585ABBE35905317029B17ABE0CBBC.5ABEE2C5E92518E88E949486C6C32F5E8A56F1BC%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D135%26clen%3D18202618%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=135&clen=18202618&init=0-708,lmt=1404096460566033&index=235-938&bitrate=553416&size=854x480&type=video%2Fwebm%3B+codecs%3D%22vp9%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404096460566033%26mv%3Dm%26dur%3D208.275%26ipbits%3D0%26signature%3DD62E4E4CE92F189E948E06390CA1050E2D8AD219.2EC40FA43C5383023666A85328E88CCB2F24662D%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D244%26clen%3D11648621%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=244&clen=11648621&init=0-234,lmt=1403869314567657&index=709-1244&bitrate=529609&size=640x360&type=video%2Fmp4%3B+codecs%3D%22avc1.4d401e%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869314567657%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3DB8F060E2FC641F4C88DF88848666CCB2651F91DD.DCC8301C29399AC35D9648D799A7D37BCD4E9330%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D134%26clen%3D8959727%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=134&clen=8959727&init=0-708,lmt=1404096464436608&index=235-938&bitrate=282271&size=640x360&type=video%2Fwebm%3B+codecs%3D%22vp9%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404096464436608%26mv%3Dm%26dur%3D208.275%26ipbits%3D0%26signature%3D0F5E2AD86944BD38695CEF00A18B221C7A9A704F.F6686CDA3B2402796256454871AA0033F50ED2A5%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D243%26clen%3D5964298%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=243&clen=5964298&init=0-234,lmt=1403869310081907&index=673-1208&bitrate=293550&size=426x240&type=video%2Fmp4%3B+codecs%3D%22avc1.4d4015%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869310081907%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3D17593FC984A1590D8045F39BF910BA3ABF23C243.58F53CEF86AFC3CE4F2608EEA46DFCC6F168E82E%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D133%26clen%3D6389750%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=133&clen=6389750&init=0-672,lmt=1404096446264449&index=234-936&bitrate=145190&size=426x240&type=video%2Fwebm%3B+codecs%3D%22vp9%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404096446264449%26mv%3Dm%26dur%3D208.275%26ipbits%3D0%26signature%3D689660BE1E76E31D8A7233B60729DE7316AEE318.012B6BDEBDD50C3462C16A8214C918F147F99B6B%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D242%26clen%3D3055498%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=242&clen=3055498&init=0-233,lmt=1403869308571975&index=671-1206&bitrate=110444&size=256x144&type=video%2Fmp4%3B+codecs%3D%22avc1.42c00c%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869308571975%26mv%3Dm%26dur%3D208.308%26ipbits%3D0%26signature%3DBDCD5656CF17F0CA43AEA0C7770EE3AC0805E17F.8133DB3A94299BDEAD8F3B1427520F2AE3CAECD2%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D160%26clen%3D2770945%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=160&clen=2770945&init=0-670,lmt=1403869308044864&index=592-875&bitrate=129354&type=audio%2Fmp4%3B+codecs%3D%22mp4a.40.2%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1403869308044864%26mv%3Dm%26dur%3D208.375%26ipbits%3D0%26signature%3DD76C56AFA403CB85A7C600A40A3B4E31C0D1AE58.08A3D9C4C95CD0530F0A22A32F7DE495897BEC1E%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D140%26clen%3D3345879%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=140&clen=3345879&init=0-591,lmt=1404095847160059&index=4452-4805&bitrate=119559&type=audio%2Fwebm%3B+codecs%3D%22vorbis%22&url=http%3A%2F%2Fr3---sn-8qj-nbo6.googlevideo.com%2Fvideoplayback%3Fsparams%3Dclen%252Cdur%252Cgir%252Cid%252Cip%252Cipbits%252Citag%252Clmt%252Csource%252Cupn%252Cexpire%26source%3Dyoutube%26lmt%3D1404095847160059%26mv%3Dm%26dur%3D208.316%26ipbits%3D0%26signature%3D2ACA16F3FD5DFEC88BEAE43D0B074F05CF809500.5BEF4A6D5897B0FF835E21EE8725672A7444E736%26key%3Dyt5%26ip%3D123.21.12.150%26gir%3Dyes%26mws%3Dyes%26upn%3DhM9MygXhics%26fexp%3D902408%252C906010%252C913587%252C924213%252C924217%252C924222%252C930008%252C930811%252C931324%252C934024%252C934030%26sver%3D3%26expire%3D1404302400%26mt%3D1404279919%26itag%3D171%26clen%3D2601724%26id%3Do-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5%26ms%3Dau&itag=171&clen=2601724&init=0-4451",
    "ucid": "UCyQobySFx_h9oFwsBV0KGdg",
    "host_language": "en",
    "ytfocHistoryEnabled": "1",
    "atc": "a=3&b=am33xK-kr_Ix8Gt9xhmHsm_EoSM&c=1404279961&d=1&e=yXRVtKo1xpA&c3a=21&c1a=1&hh=PdH7wPpoPeSKH5m6E3jKHRBF1e4",
    "video_id": "yXRVtKo1xpA",
    "loaderUrl": "http:\/\/www.youtube.com\/watch?v=yXRVtKo1xpA",
    "vid": "yXRVtKo1xpA",
    "focEnabled": "1",
    "tmi": "1",
    "sendtmp": "1",
    "keywords": "",
    "storyboard_spec": "http:\/\/i1.ytimg.com\/sb\/yXRVtKo1xpA\/storyboard3_L$L\/$N.jpg|48#27#100#10#10#0#default#aT4Q3ARlF0XF33lPE4Drr7Yy5ck|80#45#106#10#10#2000#M$M#l4lMQwGpFhA1EMTC24IOH3MPUdE|160#90#106#5#5#2000#M$M#cmzkykhNcLo0jEuDdKI02ourilQ",
    "c": "WEB",
    "ytfocEnabled": "1",
    "dashmpd": "http:\/\/manifest.googlevideo.com\/api\/manifest\/dash\/sparams\/as%2Ccmbypass%2Cid%2Cip%2Cipbits%2Citag%2Cplayback_host%2Csource%2Cexpire\/source\/youtube\/mws\/yes\/mv\/m\/ipbits\/0\/signature\/AE83796B41505CF5D8A596DA0E89868102C973CD.2533ED8186F11739986D68A977808F221CD27190\/key\/yt5\/ip\/123.21.12.150\/upn\/DbJC9YLuo_o\/playback_host\/r3---sn-8qj-nbo6.googlevideo.com\/as\/fmp4_audio_clear%2Cwebm_audio_clear%2Cfmp4_sd_hd_clear%2Cwebm_sd_hd_clear\/fexp\/902408%2C906010%2C913587%2C924213%2C924217%2C924222%2C930008%2C930811%2C931324%2C934024%2C934030\/sver\/3\/expire\/1404302400\/mt\/1404279919\/itag\/0\/cmbypass\/yes\/id\/o-AOeSPAnBzYVVfLAiLuEn0nNGnczf_8evRmRlShevH8C5\/ms\/au",
    "rmktPingThreshold": 0,
    "length_seconds": 209,
    "csi_page_type": "watch,watch7",
    "pltype": "contentugc",
    "no_get_video_log": "1",
    "idpj": "-6",
    "cr": "VN",
    "watermark": ",http:\/\/s.ytimg.com\/yts\/img\/watermark\/youtube_watermark-vflHX6b6E.png,http:\/\/s.ytimg.com\/yts\/img\/watermark\/youtube_hd_watermark-vflAzLcD6.png",
    "referrer": null,
    "dash": "1",
    "t": "1",
    "enablejsapi": 1,
    "ptk": "youtube_none",
    "enablecsi": "1",
    "plid": "AAT9L2hD0Beuz5a7",
    "cosver": "6.1",
    "fmt_list": "22\/1280x720\/9\/0\/115,43\/640x360\/99\/0\/0,18\/640x360\/9\/0\/115,5\/320x240\/7\/0\/0,36\/320x240\/99\/1\/0,17\/176x144\/99\/1\/0",
    "flexwatch_enabled": "1"
	}
</code>
	 * 
	 * @param res
	 * @param html
	 * @throws UnsupportedEncodingException
	 * @throws JSONException
	 */
	private static void extractInfo(VideoPlayEntry res, String html)
			throws UnsupportedEncodingException, JSONException {
		// Parse the HTML response and extract the streaming URIs
		if (html.contains("verify-age-thumb")) {
			// "YouTube is asking for age verification. We can't handle that sorry."
			return;
		}

		if (html.contains("das_captcha")) {
			// please try with different IP address.
			return;
		}

		Matcher argument = Pattern.compile("args\": \\{(.*?)?\\}").matcher(html);
		String argumentString = null;
		if (argument.find()) {
			argumentString = argument.group();
		}

		if (StringUtils.isBlank(argumentString)) {
			return;
		}
		html = null;

		JSONObject json = new JSONObject(argumentString.substring("args\":".length()));

		if (json.has("title")) {
			res.setTitle(json.getString("title"));
		}

		//
		// try {
		// FileUtils.writeByteArrayToFile(
		// new File(Environment.getExternalStorageDirectory(),
		// "player jsonlog.txt"), json.toString().getBytes());
		// } catch (Throwable e) {
		// e.printStackTrace();
		// }

		// if (json.has("rvs")) {
		// Log.d("videoJson",
		// URLDecoder.decode(json.getString("rvs"), "UTF-8"));
		// }
		//
		// if (json.has("list")) {
		//
		// } else {
		//
		// }

		if (json.has("url_encoded_fmt_stream_map")) {
			HashMap<String, YoutubeUrlMeta> typeMap = YoutubeUrlMeta.getMetaMap();
			String urls[] = json.getString("url_encoded_fmt_stream_map").split(",");
			for (String ppUrl : urls) {
				String url = URLDecoder.decode(ppUrl, "UTF-8");

				String itag = extraITag(url);
				if (itag != null) {
					String videoUrl = extractUrl(ppUrl);
					if (videoUrl != null) {
						YoutubeUrlMeta meta = typeMap.get(itag);
						if (meta != null) {
							meta.setTitle(res.getTitle());
							meta.setVideoSrc(videoUrl);
							res.addUrl(meta);
						}
					}
				} else {
					if (res.getTitle() == null) {
						if (url.startsWith("\"title\":")) {
							res.setTitle(url.substring("\"title\":".length()));
						}
					}
				}
			}
		}
	}

	private static String extractUrl(String ppUrl) {
		try {
			Pattern p2 = Pattern.compile("sig=(.*?)[&]");
			Matcher m2 = p2.matcher(ppUrl);
			String sig = null;
			if (m2.find()) {
				sig = m2.group(1);
			}

			Pattern p3 = Pattern.compile("url=(.*?)[&]");
			Matcher m3 = p3.matcher(ppUrl);
			String um = null;
			if (m3.find()) {
				um = m3.group(1);
			}

			return URLDecoder.decode(um, "UTF-8") + "&" + "signature=" + sig;
		} catch (Throwable e) {
			return null;
		}
	}

	private static String extraITag(String url) {
		Pattern p1 = Pattern.compile("itag=([0-9]+?)[&]");
		Matcher m1 = p1.matcher(url);
		String itag = null;
		if (m1.find()) {
			itag = m1.group(1);
		}
		return itag;
	}

	public static final YoutubeUrlMeta getBestUrl(List<YoutubeUrlMeta> urls, int screenWidth, int screenHeight) {
		if (urls == null) {
			return null;
		}

		int screenEdge = Math.max(screenWidth, screenHeight);
		int bestDiff = Integer.MAX_VALUE;
		YoutubeUrlMeta res = null;
		for (YoutubeUrlMeta meta : urls) {
			int currentDif = Math.abs(Math.max(meta.width, meta.height) - screenEdge);
			if (currentDif < bestDiff) {
				bestDiff = currentDif;
				res = meta;
			}
		}

		return res;
	}
}
